package com.luosonxin.controller;/*
 * @Author:lsx
 * @Date:2024/12/7--12--07--20:34
 *
 */

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.luosonxin.bean.Book;
import com.luosonxin.bean.User;
import com.luosonxin.service.BookService;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/book")
public class BookController {
    @Resource
    private BookService bookService;
    @GetMapping("/getBooks")
    @ResponseBody
    public Object getBooks(Book book,
                           Date beginDate,
                           Date endDate,
                           @RequestParam(required = false,defaultValue = "1") int pageNum,
                           @RequestParam(required = false,defaultValue = "10") int pageSize){
        PageHelper.startPage(pageNum,pageSize);
        Page<Book> page = (Page<Book>)bookService.selectBookByCondition(book, beginDate, endDate);
        return page.toPageInfo();
    }
    @PostMapping("/addBook")
    public String insertBook(MultipartFile bookImage,@Valid Book book,Model model,  BindingResult bindingResult){
        if (bookImage == null && bookImage.isEmpty() && !bookImage.getContentType().contains("image")){
            model.addAttribute("msg","文件不能为空");
            return "redirect:/bookAdd";
        }
        int i =bookService.insertBook(book);
        if (bindingResult.hasErrors()){
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            Map<String, String> map = new HashMap<>();
            for (FieldError fieldError : fieldErrors) {
                map.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            model.addAttribute("errors", map);
            return "redirect:/bookAdd";
        }
        if(bookImage != null && !bookImage.isEmpty() && bookImage.getContentType().contains("image")){
            try {
                String fileName = bookImage.getOriginalFilename();
                String newFileName = System.currentTimeMillis() + fileName;
                String savePath = "c:/bookCover/" + newFileName;//确定 文件存储的路径
                String visitPath = "/luosonxin/bookCover/" + newFileName;
                bookImage.transferTo(new File(savePath));
                List<Book> books = bookService.selectBookByCondition(book, null, null);
                if (!books.isEmpty()) {
                    Book book1 = books.get(0);
                    int id = book1.getBookId();
                    bookService.updateBookImage(visitPath, id);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        model.addAttribute("msg","添加成功");
        return "redirect:/books";
    }
    @GetMapping("/selectBookById")
    public String selectBookById(int bookId,Model model){
        Book book = bookService.selectBookById(bookId);
        model.addAttribute("book",book);
        return "forward:/WEB-INF/book.jsp";
    }
    @RequestMapping("/deleteBook")
    @ResponseBody
    public String deleteBook(int bookId){
        Book book = bookService.selectBookById(bookId);
        int i= bookService.deleteBookByBookId(bookId);
        if (i == 1) {
            String visitPath = book.getBookCover();
            String realPath = visitPath.replaceAll("/luosonxin/","c:/");
            if(!realPath.equals("c:/bookCover/default.jpg")) {
                new File(realPath).delete();
            }
        }
        return i == 1 ? "success" : "fail";
    }
    @PostMapping("/updateBook")
    public String updateBook(MultipartFile bookImage,@Valid Book book,Model model){
        int i = bookService.updateBook(book);
        if(i!= 1){
             model.addAttribute("msg","修改失败");
             return "forward:/WEB-INF//updateBook.jsp";
        }

        //删除旧图片
        if (i == 1) {
            String visitPath = bookService.selectBookById(book.getBookId()).getBookCover();
            String realPath = visitPath.replaceAll("/luosonxin/","c:/");
            if(!realPath.equals("c:/bookCover/default.jpg")) {
                new File(realPath).delete();
            }
        }
        //上传新图片
        if(bookImage != null && !bookImage.isEmpty() && bookImage.getContentType().contains("image")){
            try {
                String fileName = bookImage.getOriginalFilename();
                String newFileName = System.currentTimeMillis() + fileName;
                String savePath = "c:/bookCover/" + newFileName;//确定 文件存储的路径
                String visitPath = "/luosonxin/bookCover/" + newFileName;
                bookImage.transferTo(new File(savePath));
                List<Book> books = bookService.selectBookByCondition(book, null, null);
                if (!books.isEmpty()) {
                    Book book1 = books.get(0);
                    int id = book1.getBookId();
                    bookService.updateBookImage(visitPath, id);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return "redirect:/books";
    }
    @RequestMapping("toUpdateBook")
    public String toUpdateBook(int bookId,Model model){
        Book book = bookService.selectBookById(bookId);
        System.out.println(book);
        model.addAttribute("book",book);
        return "forward:/WEB-INF/updateBook.jsp";
    }
}
